
class Enlarge
{
    // this = enlarge1/enlarge2
    constructor(el)
    {
        // this  enlarge1/enlarge2

        // 初始化全局数据
        this.el = document.querySelector(el)
        this.imgObj = this.el.querySelector('.img')
        this.maskObj = this.el.querySelector('.mask')
        this.enlargeObj = this.el.querySelector('.enlarge')

        // 启动插件
        this.init()  
    }

    // 启动插件
    init() {
        this.overOut()
        this.maskMove()
        // this.tbEnlarge()
    }

    // 鼠标在图片上移入移出
    overOut()
    {
        // this enlarge1/enlarge2
        // // 1 给左侧图绑定移入事件 
        // this.imgObj.onmouseover = function() {  // this 事件源
        // this.imgObj.onmouseover = () => {  // this 事件源
        //     // 2 事件处理函数中-显示遮罩框
        //     this.maskObj.style.display = 'block'
        //     // 3 事件处理函数中-放大镜
        //     this.enlargeObj.style.display = 'block'
        // }

        // 1 给左侧图绑定移入事件
        // 2 事件处理函数中-显示遮罩框
        // 3 事件处理函数中-放大镜
        this.imgObj.onmouseover = () => this.maskObj.style.display = this.enlargeObj.style.display =  'block'
        this.imgObj.onmouseout = () => this.maskObj.style.display = this.enlargeObj.style.display =  'none'

    }

    // 鼠标移动
    maskMove() 
    {
        // this enlarge1/enlarge2

        // 1 给左侧图片绑定鼠标移动事件
        // this.imgObj.onmousemove = function(evt) { // this this.imgObj
        this.imgObj.onmousemove = (evt) => { // this  enlarge1/enlarge2
        // this.imgObj.onmousemove = evt => { // this  enlarge1/enlarge2
            // 2 事件处理函数中 - 获取事件对象
            let e = evt || window.event
            // 3 事件处理函数中 - 计算mask移动left/top
            let left = e.pageX - this.imgObj.offsetLeft - this.maskObj.offsetWidth/2
            let top = e.pageY - this.imgObj.offsetTop  - this.maskObj.offsetHeight/2
            // 4 事件处理函数中 - 边界限制
            if (left<0) left=0
            if (top<0) top=0
            let maxLeft = this.imgObj.offsetWidth - this.maskObj.offsetWidth
            let maxTop = this.imgObj.offsetHeight - this.maskObj.offsetHeight
            if (left>maxLeft) left = maxLeft
            if (top>maxTop) top = maxTop
            // 5 事件处理函数中 - 设置遮罩框的left/top
            this.maskObj.style.left = left + 'px'
            this.maskObj.style.top = top + 'px'


            // 同步
            this.tbEnlarge(left, top)
        }
    }

    // 鼠标移动，同步放大镜效果
    tbEnlarge(left, top) 
    {
        // this enlarge1/enlarge2
        this.enlargeObj.style.backgroundPosition = `-${left*2}px -${top*2}px`
    }
}

export default Enlarge